package com.motu.monstercity.server.game.logic;

import com.motu.monstercity.module.common.network.ResponseUtils;
import com.motu.monstercity.module.common.utility.Constant;
import com.motu.monstercity.protocol.Common;
import com.motu.monstercity.protocol.Common.PBMarryInfo;
import com.motu.monstercity.protocol.Common.PBUserData;
import com.motu.monstercity.protocol.CsGameChild.PBUserGraduationInfo;
import com.motu.monstercity.protocol.CsGameSystem;
import com.motu.monstercity.protocol.CsGameSystem.CSGameSystemRedPointResponse;
import com.motu.monstercity.server.game.base.AllParam;
import com.motu.monstercity.server.game.base.CommonUtils;
import com.motu.monstercity.server.game.base.ProtoDataUtils;
import com.motu.monstercity.server.game.commondata.child.ChildConstant;
import com.motu.monstercity.server.game.commondata.child.ChildQuality;
import com.motu.monstercity.server.game.commondata.iap.PrivilegeCardConstant;
import com.motu.monstercity.server.game.commondata.mail.MailConstant;
import com.motu.monstercity.server.game.commondata.maintask.MainTaskConstant;
import com.motu.monstercity.server.game.commondata.partner.PartnerMain;
import com.motu.monstercity.server.game.commondata.skill.Skill;
import com.motu.monstercity.server.game.commondata.rank.RankConstant;
import com.motu.monstercity.server.game.commondata.secretary.SecretaryMain;
import com.motu.monstercity.server.game.commondata.skill.SkillConstant;
import com.motu.monstercity.server.game.commondata.system.UserExp;
import com.motu.monstercity.server.game.log.LogType;
import com.motu.monstercity.server.game.userdata.*;
import com.motu.vertx.module.utility.model.EntityManager;

import com.motu.vertx.module.utility.redis.RedisTools;
import com.motu.vertx.module.utility.toolset.TimeUtils;
import com.motu.vertx.module.utility.toolset.Tool;
import io.vertx.core.Future;
import io.vertx.core.json.JsonArray;
import io.vertx.core.json.JsonObject;

import java.util.List;
import java.util.Map;


public class ChildManager extends ChildUserData{
    // 初始化 下发子嗣模块的用户数据
    public static void loadInitChildUserData(PBUserData.Builder pbUserData, UserInfo userInfo) {
        long userId = userInfo.getId();
        UserChildInfo userChildInfo = getUserChildInfo(userId);
        ProtoDataUtils.updatePBUserData(pbUserData, userChildInfo, true);

        for (UserChildCls userChildCls : getUserChildClsList(userId)) {
            ProtoDataUtils.updatePBUserData(pbUserData, userChildCls, true);
        }
    }

    // 生小孩,创建小孩数据
    public static void createChild(PBUserData.Builder pbUserData, UserChildCls cls, UserPartner userPartner, UserSecretary userSecretary, boolean isTwins) {
        int partnerId = userPartner.getPartnerId();
        PartnerMain partnerMain = PartnerManager.getPartnerMain(partnerId);
        SecretaryMain secretaryMain = SecretaryManager.getSecretaryMain(userSecretary.getSecretaryId());
        //随机性格
        int character;
        int index = Tool.getWeightIndex(AllParam.CHILD_CHARACTER_RATE);//一定概率随母亲，一定概率随父亲，一定概率所有性格随机
        if (index == 0){
            character = partnerMain.getCharacterType();
        } else if (index == 1){
            character = secretaryMain.getDisposition();
        } else {
            character = ChildConstant.CHARACTER_LIST[Tool.getIntRandom(ChildConstant.CHARACTER_LIST.length)];
        }
        //随机职业
        int career = ChildManager.randomChildCareer();
        //生成子嗣到教室中
        cls.putStudySchedule(0);//教学进度
        cls.putCareer(career);//职业
        cls.putCareerAddition(Tool.getRandom(AllParam.CHILD_CAREER_ADDITION[0], AllParam.CHILD_CAREER_ADDITION[1]));//职业加成
        cls.putPartner(partnerId);//父亲(父母不看性别)
        cls.putPartnerAddition(userPartner.takeChildAdd());//父亲加成
        cls.putSecretary(userSecretary.getSecretaryId());//母亲(父母不看性别)
        cls.putSecretaryAddition((int)(userSecretary.takeChildAdd() * 10000));//母亲加成
        cls.putQuality((byte) userSecretary.getIdentitySkillLevel());//继承母亲当前的品质, 秘书基因技能升级几次就哪个品质，初始升级1次
        cls.putAppearance((byte) (Tool.checkRandom(AllParam.CHILD_APPEARANCE_RATE/100) ? 0 : 1));//随机外观随父亲或者母亲
        cls.putCharacterId((byte) character);//性格
        cls.putIsTwins((byte)(isTwins ? 1 : 0));//是否双胞胎
        if (isTwins){
            cls.putSisterSex((byte) (Tool.checkRandom(Constant.FIFTY) ? 1 : 0));//双胞胎另一个的性别
            cls.putSisterName("");
        }
        cls.putSex((byte) (Tool.checkRandom(Constant.FIFTY) ? 1 : 0));//性别
        cls.putName("");
        cls.putIsStudy((byte) 1);//教室状态为有子嗣上课
        cls.putAddition(0);

        int childNum = isTwins ? 2 : 1;// 获得子嗣的数量
        UserInfo userInfo = GameUser.getUserInfo(cls.getUserId());
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_117, childNum);// 更新主线任务,成就,日常任务的进度
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_117, childNum);
    }

    // 子嗣 城市收益加成的基础值
    public static long countEarnAddBaseValue(UserInfo userInfo, UserChildCls userChildCls, UserExp userExp){
        UserSecretary userSecretary = SecretaryManager.getUserSecretary(userInfo.getId(), userChildCls.getSecretary());
        UserPartner userPartner = PartnerManager.getUserPartner(userInfo.getId(), userChildCls.getPartner());
        if (userSecretary == null || userPartner == null) {
            return 0L;
        }

        int childBasePower = userExp.getChildBasePower();

        double basePower = userExp.getChildBasePower2();

        double motherAdd = userSecretary.takeChildAdd();// 母亲的加成系数0.74 （母亲魅力值* 10000）/（母亲魅力值 + 20000） 削弱

        basePower = basePower *  motherAdd;

        int levelAdd = userExp.getChildAddition();// userexp表的child_addition字段/10000）

        int qualityAdd = userChildCls.takeQualityEarnAdd();// 品质加成系数 12500

        int careerAdd = userChildCls.getCareerAddition();// 职业加成系数

        int partnerAdd = userPartner.takeChildAdd();// 干员加成

        int skillAdd = SkillManager.getSkillMoudleAdd(userInfo.getId(), SkillConstant.EFFECT_TYPE_5, userChildCls.getCharacterId());// 干员技能加成,秘书技能加成

        double total = childBasePower + basePower * (10000 + levelAdd) /10000  * (qualityAdd + careerAdd + partnerAdd + skillAdd) / 10000;
        return (long) Math.floor(total);
    }

    // 验证是否未婚子嗣数量是否达到上限
    public static boolean checkUnMarryNum(UserChildCls userChildCls, long userId) {
        JsonArray list = EntityManager.getEntityKeyList(UserChildUnmarried.class, userId);
        //双胞胎的特殊情况
        if (userChildCls.checkIsTwins() && list.size() + 2 > AllParam.CHILD_UNMARRIED_MAX){
            return false;
        }
        if (!userChildCls.checkIsTwins() && list.size() + 1 > AllParam.CHILD_UNMARRIED_MAX){
            return false;
        }
        return true;
    }

    // 解锁教室
    public static void unlockClassRoom(PBUserData.Builder pbUserData, UserInfo userInfo) {
        UserExp userExp = GameDataManager.getUserExp(userInfo.getLevel());
        int energy = takeChildRoomEnergyMax(userInfo);
        for (int i = 0; i < AllParam.SON_NUM_LEVEL.length; i++) {
            int level = AllParam.SON_NUM_LEVEL[i];
            if (userInfo.getLevel() >= level) {
                int clsId = i + 1;
                UserChildCls userChildCls = getUserChildCls(userInfo.getId(), clsId);
                if (userChildCls == null) {// 未解锁
                    userChildCls = new UserChildCls(userInfo.getId(), clsId);
                    userChildCls.putEnergy(energy);
                    userChildCls.putEnergyRecoverTime(TimeUtils.getCurTime());
                    userChildCls.doCreate();
                    ProtoDataUtils.updatePBUserData(pbUserData, userChildCls, true);
                }
            }
        }
    }

    /**
     * 获取 pbUserGraduationInfo
     * @param cls
     * @return  // 生成小孩的数据, index 第几个小孩,双胞胎的情况,0 第一个,1双胞胎的第二个
     */
    public static PBUserGraduationInfo.Builder getPbUserGraduationInfo(UserChildCls cls, int aloneAddition, int qualityAddition, int index){
        PBUserGraduationInfo.Builder pbUserGraduationInfo = PBUserGraduationInfo.newBuilder();
        pbUserGraduationInfo.setName(index == 1 ? cls.getSisterName() : cls.getName());
        pbUserGraduationInfo.setQuality(cls.getQuality());
        pbUserGraduationInfo.setCareer(cls.getCareer());
        if (cls.checkIsTwins()) {
            pbUserGraduationInfo.setAddition((int)(cls.getAddition()/2));
        } else {
            pbUserGraduationInfo.setAddition((int)cls.getAddition());
        }
        pbUserGraduationInfo.setPartner(cls.getPartner());
        pbUserGraduationInfo.setSecretary(cls.getSecretary());
        pbUserGraduationInfo.setCareerAddition(cls.getCareerAddition());
        pbUserGraduationInfo.setPartnerAddition(cls.getPartnerAddition());
        UserSecretary userSecretary = SecretaryManager.getUserSecretary(cls.getUserId(), cls.getSecretary());
        pbUserGraduationInfo.setSecretaryAddition((int)(userSecretary.takeChildAdd() * 10000));
        pbUserGraduationInfo.setQualityAddition(qualityAddition);
        pbUserGraduationInfo.setCharacterId(cls.getCharacterId());
        pbUserGraduationInfo.setSex(index == 1 ? cls.getSisterSex() : cls.getSex());
        pbUserGraduationInfo.setAloneAddition(ChildManager.takeEranAddAlone());
        pbUserGraduationInfo.setSkillAddition(SkillManager.getSkillMoudleAdd(cls.getUserId(), SkillConstant.EFFECT_TYPE_5, cls.getCharacterId()));
        return pbUserGraduationInfo;
    }

    // 玩家教室的体力上限
    public static int takeChildRoomEnergyMax(UserInfo userInfo) {
        UserExp userExp = GameDataManager.getUserExp(userInfo.getLevel());
        int max = userExp == null ? 0 : userExp.getChildAddTrainNum();
        int privilegeCardAdd = IapManager.takePrivilegeValueByType(userInfo.getId(), PrivilegeCardConstant.TYPE_CHILD_NUM);// 特权卡加成

        int total = max + privilegeCardAdd;
        return total;
    }

    // 是否解锁一键上课功能
    public static boolean checkStudyOnekey(UserInfo userInfo) {
        if (IapManager.takePrivilegeValueByType(userInfo.getId(), "is_child_shcool") > 0) {
            return true;
        } else {
            return false;
        }
    }

    // 孤独终老的城市收益加成 200%- 750% 返回20000-75000
    public static int takeEranAddAlone () {
        int random = Tool.getRandom(AllParam.CHILD_ALONE_ADDITION[0], AllParam.CHILD_ALONE_ADDITION[1]);
        return random;
    }

    // 子嗣培养该进度对应的培养节点
    public static int takeNodeNum(int value) {
        int nodeNum = AllParam.CHILD_COURSE_MAX / AllParam.CHILD_COURSE_STAGE;// 节点数量
        for (int i=1; i<=nodeNum; i++) {
            if (value >= AllParam.CHILD_COURSE_STAGE * i && value < AllParam.CHILD_COURSE_STAGE * (i + 1)) {
                return i;
            }
        }
        return 0;
    }

    // 毕业的性格奖励的道具数量
    public static int takeGraduateRewardItemNum(int qualityId) {
        ChildQuality childQuality = ChildManager.getChildQuality(qualityId);
        if (childQuality == null) {
            return 0;
        }
        return childQuality.getRewardItem();
    }

    // 子嗣培养的红点提示
    public static boolean checkRedPointStudy(CSGameSystemRedPointResponse.Builder builder, UserInfo userInfo){
        CsGameSystem.RedPoint_Child.Builder redPointChild = CsGameSystem.RedPoint_Child.newBuilder();
        List<UserChildCls> childClsList = getUserChildClsList(userInfo.getId());
        for (UserChildCls userChildCls : childClsList) {
            if (userChildCls.checkRedPointStudy()) {
                redPointChild.addStudy(userChildCls.getClsId());
            }
        }

        if (redPointChild.getStudyCount() > 0) {
            builder.setChild(redPointChild);
            return true;
        } else {
            return false;
        }
    }

    // 统计单次上课获得经验总数量,秘书技能类型22会有加成 获得的 100003 数量
    public static long countStudyExpNum(long userId, UserChildCls userChildCls, UserExp userExp) {
        ChildQuality childQuality = ChildManager.getChildQuality(userChildCls.getQuality());
        int skillAdd = SkillManager.getSkillMoudleAdd(userId, SkillConstant.EFFECT_TYPE_22, userChildCls.getCharacterId());// 干员技能加成,秘书技能加成

        double total = userExp.getChildTrainAddExp();
        total = total * childQuality.getPartnerExpAddition() / 10000;
        total = total + total * skillAdd / 10000;

        return (long)Math.floor(total);
    }

    // 教室的每次上课获得的干员经验的秘书基因加成 放大1W倍
    public static int countStudySecrSkillAdd(UserChildCls userChildCls, List<UserSecretary> userSecretaryList) {
        int total = 0;
        for (UserSecretary userSecretary : userSecretaryList) {
            for (Map.Entry<Integer, Integer> entry : userSecretary.takeSkillMap().entrySet()) {
                int skillId = entry.getKey();
                int level = entry.getValue();
                Skill skill = SkillManager.getSkill(skillId);
                boolean isAdd = isAdd(userChildCls, skill);
                if (isAdd) {
                    total += skill.countTotalAdd(level);
                }
            }
        }
        return total;
    }

    // 是否有加成
    private static boolean isAdd(UserChildCls userChildCls, Skill skill) {
        boolean isAdd = false;// 该技能是否对这个小孩有加成效果
        if (skill.getEffectParam() == 0) {// 所有小孩都有加成
            isAdd = true;
        } else if (skill.getEffectParam() == userChildCls.getCharacterId()) {// 性格一致也有加成
            isAdd = true;
        } else if (skill.getEffectParam() == 6 && userChildCls.getSex() == 1) {// 配置6,所有男性的小孩才有加成
            isAdd = true;
        } else if (skill.getEffectParam() == 7 && userChildCls.getSex() == 0) {// 配置7,所有女性的小孩才有加成
            isAdd = true;
        }
        return isAdd;
    }

    // 购买完特权卡,给所有教室增加体力
    public static void addAllChildClsEnergy(PBUserData.Builder pbUserData, UserInfo userInfo, int addValue) {
        int max = takeChildRoomEnergyMax(userInfo);// 体力上限
        for (UserChildCls userChildCls : getUserChildClsList(userInfo.getId())) {
            userChildCls.addEnergy(addValue);
            userChildCls.update();
            ProtoDataUtils.updatePBUserData(pbUserData, userChildCls);
        }
    }

    // 创建全服征婚数据
    public static void createServerMarry(UserInfo userInfo, UserChildUnmarried userChildUnmarried, long minEarn) {
        ServerMarryInfo serverMarryInfo = new ServerMarryInfo(userInfo.getServerId(), userInfo.getId(), userChildUnmarried.getId(), minEarn, userChildUnmarried.getSex());
        serverMarryInfo.doCreate();
        if (userChildUnmarried.isMale()) {// 男性
            updateMarryPublicRank(RankConstant.SERVER_RANK_MARRY_MALE, userInfo.getServerId(), userInfo.getId(), userChildUnmarried.getId());
        } else {
            updateMarryPublicRank(RankConstant.SERVER_RANK_MARRY_FEMALE, userInfo.getServerId(), userInfo.getId(), userChildUnmarried.getId());
        }
    }

    // 更新全服征婚数据的榜单，用来随机刷新匹配到的征婚数据用
    public static void updateMarryPublicRank(int rankType, int serverId, long userId, long childId) {
        String rankName = RankManager.getRankName(rankType, serverId, 0);
        int random = Tool.getRandom(100001, 199999);// 随机数
        RedisTools.addRank(rankName, childId, random);
    }

    // 刷新匹配到的可联姻数据
    public static void refreshMatchInfo(UserInfo userInfo, UserChildUnmarried userChildUnmarried) {
        int serverId = userInfo.getServerId();
        int rankType = userChildUnmarried.isMale() ? RankConstant.SERVER_RANK_MARRY_FEMALE : RankConstant.SERVER_RANK_MARRY_MALE;//只能异性结婚
        String rankName = RankManager.getRankName(rankType, serverId, 0);
        long total = Future.await(RedisTools.getRankLen(rankName));// 总的有多少个征婚数据
        int max = (int) total;
        int random = Tool.getRandom(0, max);
        int ss = Math.max(0, random - 10);// 起始
        int ee = Math.min(max - 1, random + 10);// 结束
        JsonArray list = Future.await(RedisTools.getRankListByIndex(rankName, ss, ee, false));
        JsonArray jsonArray = new JsonArray();
        for (int i=0;i<list.size();i++) {
            long childId = Long.parseLong(list.getString(i));
            ServerMarryInfo serverMarryInfo = getServerMarryInfo(serverId, childId);
            if (serverMarryInfo.isExpire()) {// 已过期
                cancelMarryInfo(userInfo, userChildUnmarried, serverMarryInfo, null);// 删除servermarry数据，和 榜单数据匹配池子
            } else if (serverMarryInfo.getUserId() != userInfo.getId()) {
                jsonArray.add(childId);
            }
        }

        JsonArray newArray = filterMatchInfo(userChildUnmarried, jsonArray);// 过滤掉跟上次相同的,
        userChildUnmarried.putMatchInfo(newArray.toString());
        if (newArray.size() < AllParam.CHILD_MARRY_MATCH_INFO_MAX) {// 少于5条，生成机器人征婚数据
            int num = AllParam.CHILD_MARRY_MATCH_INFO_MAX - newArray.size();// 需要生成多少条机器人数据
            createMatchInfoRobot(userInfo, userChildUnmarried, num);
        }
    }

    // 取消征婚，删除servermarry数据，和 榜单数据匹配池子 或联姻请求
    public static void cancelMarryInfo(UserInfo userInfo, UserChildUnmarried userChildUnmarried, ServerMarryInfo serverMarryInfo, UserMarryApply userMarryApply) {
        int serverId = userInfo.getServerId();
        long childId = userChildUnmarried.getId();
        if (userChildUnmarried.isMarryServer()) {// 1-全服征婚
            int rankType = 0;
            if (serverMarryInfo == null) {
                serverMarryInfo = getServerMarryInfo(serverId, childId);// 没传值进来则取一次
            }
            if (serverMarryInfo != null) {
                serverMarryInfo.delete();
            }
            if (userChildUnmarried.isMale()) {//男性
                rankType = RankConstant.SERVER_RANK_MARRY_MALE;
            } else {// 女性
                rankType = RankConstant.SERVER_RANK_MARRY_FEMALE;
            }
            String rankName = RankManager.getRankName(rankType, serverId, 0);
            RedisTools.removeFromRank(rankName, childId);
        } else if (userChildUnmarried.isMarryUser()) {// 指定玩家
            if (userMarryApply == null) {
                userMarryApply = getUserMarryApply(userChildUnmarried.getUserIdTarget(), childId);// 没传值进来则取一次
            }
            if (userMarryApply != null) {
                userMarryApply.delete();
            }
        }
    }

    // 过滤掉跟上次相同的,
    public static JsonArray filterMatchInfo(UserChildUnmarried userChildUnmarried, JsonArray jsonArray) {
        JsonArray oldArray = userChildUnmarried.getMatchInfoArray();
        JsonArray newArray = new JsonArray();
        int count = 1;
        for (int i=0;i<jsonArray.size();i++) {
            long childId = jsonArray.getLong(i);
            if (!Tool.isInList(oldArray, childId) && count <= AllParam.CHILD_MARRY_MATCH_INFO_MAX) {
                newArray.add(childId);
                count++;
            }
        }
        return newArray;
    }

    // 少于5条，生成机器人征婚数据
    public static void createMatchInfoRobot(UserInfo userInfo, UserChildUnmarried userChildUnmarried, int num) {
        JsonArray jsonArray = new JsonArray();
        for (int i=0;i<num;i++) {
            int random = Tool.getIntRandom(AllParam.CHILD_MARRY_EARN_ADD_MAX);// 机器人的城市收益
            double earnAdd = userChildUnmarried.getEarnAdd();
            earnAdd = earnAdd * random / 10000;
            UserMarryRobot userMarryRobot = new UserMarryRobot(userChildUnmarried.getId(), userInfo.getId(), (long) earnAdd);
            userMarryRobot.doCreate();
            jsonArray.add(userMarryRobot.getId());
        }
        userChildUnmarried.putMatchInfoRobot(jsonArray.toString());
    }

    // 联姻成功，处理我方的数据，发放奖励, 生成已婚子嗣数据等
    public static void handleMarryMy(PBUserData.Builder pbUserData, UserInfo userInfo, UserChildUnmarried userChildUnmarried, long userIdTarget, String childNameTarget, int quality, int characterId, int career, int partnerId, int secretaryId, int appearance, long earnAdd) {
        long userId = userInfo.getId();
        int itemId = AllParam.CHILD_CHARACTER_REWARD[characterId - 1];// 子嗣性格奖励
        long rewardItemNum = ChildManager.takeGraduateRewardItemNum(quality);// 子嗣性格奖励数量
        RewardManager.addReward(userInfo, itemId, rewardItemNum, pbUserData, LogType.CHILD_MARRY, userChildUnmarried.getName());

        UserPower userPower = GameUser.getUserPower(userId);
        long totalEarnAdd = Math.min(earnAdd, userChildUnmarried.getEarnAdd() * AllParam.CHILD_MARRY_EARN_ADD_MAX / 10000);// 最多不能超过自己收益的5倍
        UserChildInfo userChildInfo = ChildManager.getUserChildInfo(userId);
        userChildInfo.addMarryNum(1);
        userChildInfo.update();
        ProtoDataUtils.updatePBUserData(pbUserData, userChildInfo);

        userPower.addChildEarn(pbUserData, userInfo, totalEarnAdd);

        UserInfo userInfoTarget = userIdTarget > 0 ? GameUser.getUserInfo(userIdTarget) : null;
        UserChildMarry userChildMarry = new UserChildMarry(userChildUnmarried, userInfoTarget, childNameTarget, quality, career, partnerId, secretaryId, appearance, totalEarnAdd);
        userChildMarry.doCreate();
        ProtoDataUtils.updatePBUserData(pbUserData, userChildMarry, true);

        // 删除这个子嗣的机器人数据
        List<UserMarryRobot> list = getUserMarryRobotList(userChildUnmarried.getId());
        for (UserMarryRobot entity : list) {
            entity.delete();
        }

        userChildUnmarried.delete();// 删除我方这个未婚子嗣数据
        ProtoDataUtils.deletePBUserData(pbUserData, userChildUnmarried);
    }

    // 跟玩家联姻 联姻成功，处理对方的数据，发放奖励, 生成已婚子嗣数据等
    public static void handleMarryTarget(UserInfo userInfo, UserChildUnmarried userChildUnmarried, long userIdTarget, UserChildUnmarried userChildUnmarriedTarget, ServerMarryInfo serverMarryInfo) {
        UserInfo userInfoTareget = GameUser.getUserInfo(userIdTarget);
        int itemId = AllParam.CHILD_CHARACTER_REWARD[userChildUnmarried.getCharacterId() - 1];// 子嗣性格奖励
        long itemNum = ChildManager.takeGraduateRewardItemNum(userChildUnmarried.getQuality());// 子嗣性格奖励数量
        List<RewardItem> rewardItemList = CommonUtils.takeReawrdItemFromStr(itemId, itemNum);// 奖励
        MailManager.sendSystemMailReplaceContent(userIdTarget, MailConstant.CHILD_MARRY_REWARD_TITLE, MailConstant.CHILD_MARRY_REWARD_CONTENT, rewardItemList, LogType.CHILD_MARRY, userChildUnmarriedTarget.getName(), userInfo.getUserName(), userChildUnmarried.getName());


        UserPower userPowerTarget = GameUser.getUserPower(userIdTarget);
        long totalEarnAdd = Math.min(userChildUnmarried.getEarnAdd(), userChildUnmarriedTarget.getEarnAdd() * AllParam.CHILD_MARRY_EARN_ADD_MAX / 10000);// 最多不能超过自己收益的5倍
        userPowerTarget.addChildEarn(null, userInfoTareget, totalEarnAdd);

        UserChildMarry userChildMarryTarget = new UserChildMarry(userChildUnmarriedTarget, userInfo, userChildUnmarried.getName(), userChildUnmarried.getQuality(), userChildUnmarried.getCareer(), userChildUnmarried.getPartner(), userChildUnmarried.getSecretary(), userChildUnmarried.getAppearance(), totalEarnAdd);
        userChildMarryTarget.doCreate();

        cancelMarryInfo(userInfoTareget, userChildUnmarriedTarget, serverMarryInfo, null);// 删除servermarry数据，和 榜单数据匹配池子

        // 删除对方这个子嗣的机器人数据
        List<UserMarryRobot> list = getUserMarryRobotList(userChildUnmarriedTarget.getId());
        for (UserMarryRobot entity : list) {
            entity.delete();
        }
        userChildUnmarriedTarget.delete();// 删除我方这个未婚子嗣数据
        updateMarryRankActTask(userInfo);

        //  推送数据给对方
        CsGameSystem.CSGameSystemPushDataResponse.Builder response = CsGameSystem.CSGameSystemPushDataResponse.newBuilder();
        Common.PBUserData.Builder pbUserData = response.getUserBuilder();
        ProtoDataUtils.updatePBUserData(pbUserData, userChildMarryTarget, true);
        ProtoDataUtils.deletePBUserData(pbUserData, userChildUnmarriedTarget);

        response.setType(ResponseUtils.PUSH_TIPS_TYPE_3);// 服务端给某个玩家推送提示信息的类型 发布的联姻信息被对方联姻成功

        JsonObject jsonObject = ResponseUtils.getPushResponseData(response.build().toByteArray());// 广播给其他人的数据
        GameUser.pushToUser(userIdTarget, jsonObject);
    }

    // 通知被联姻的玩家，更新联姻任务进度
    public static void updateMarryRankActTask(UserInfo userInfo) {
        CsGameSystem.CSGameSystemPushDataResponse.Builder builder = CsGameSystem.CSGameSystemPushDataResponse.newBuilder();
        PBUserData.Builder pbUserData = builder.getUserBuilder();
        RankActManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_5, 1);
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_5, 1);// 后代联姻{0}次
        MainTaskManager.addTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_118, 1);// 更新主线任务,成就,日常任务的进度
        GameUser.pushPBUserData(userInfo.getId(), builder);
    }

    // 记录子嗣中历史最高城市收益加成的子嗣快照，并更新榜单
    public static void updateRankChild(PBUserData.Builder pbUserData, UserInfo userInfo, UserChildInfo userChildInfo, UserChildCls userchildcls, long earnAddTotal) {
        if (earnAddTotal > userChildInfo.getMaxEarnAdd()) {
            RankManager.updateRank(RankConstant.SERVER_RANK_MAX_CHILD, userInfo.getServerId(), userInfo.getId(), earnAddTotal, "0");// 更新战力排行榜
            userChildInfo.putMaxEarnAdd(earnAddTotal);
            // 子嗣快照
            JsonObject jsonObject = new JsonObject();
            jsonObject.put("name", userchildcls.getName());
            jsonObject.put("career", userchildcls.getCareer());
            jsonObject.put("quality", userchildcls.getQuality());
            jsonObject.put("partner", userchildcls.getPartner());
            jsonObject.put("secr", userchildcls.getSecretary());
            jsonObject.put("appear", userchildcls.getAppearance());
            jsonObject.put("sex", userchildcls.getSex());
            userChildInfo.putMaxEarnAddInfo(jsonObject.toString());

            MainTaskManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_179, earnAddTotal);// 更新主线任务,成就,日常任务的进度
            RankActManager.updateTaskProgress(pbUserData, userInfo, MainTaskConstant.TASK_TYPE_179, earnAddTotal);
        }
    }

    // 构建PBMarryInfo.Builder 数据
    public static PBMarryInfo.Builder takePBMarryInfo(UserInfo userInfo, UserChildUnmarried userChildUnmarried) {
        PBMarryInfo.Builder builder = PBMarryInfo.newBuilder();
        if (userInfo != null && userChildUnmarried != null) {
            builder.setDbid(userChildUnmarried.getId());//
            builder.setUid(userChildUnmarried.getUserId());//
            builder.setUserName(userInfo.getUserName());//
            builder.setChildName(userChildUnmarried.getName());//
            builder.setSex(userChildUnmarried.getSex());//
            builder.setQuality(userChildUnmarried.getQuality());//
            builder.setCareer(userChildUnmarried.getCareer());//
            builder.setPartner(userChildUnmarried.getPartner());//
            builder.setSecretary(userChildUnmarried.getSecretary());//
            builder.setAppearance(userChildUnmarried.getAppearance());//
            builder.setEarnAdd(userChildUnmarried.getEarnAdd());//
        }
        return builder;
    }

    // 删除联姻请求
    public static void deleteMarryApply(UserMarryApply userMarryApply) {
        UserChildUnmarried userChildUnmarriedFrom = getUserChildUnmarried(userMarryApply.getUserIdFrom(), userMarryApply.getChildIdFrom());
        if (userChildUnmarriedFrom != null) {
            userChildUnmarriedFrom.putMarryTime(0);
            userChildUnmarriedFrom.putMarryState((byte)0);
            userChildUnmarriedFrom.putUserIdTarget(0);
            userChildUnmarriedFrom.update();
        }
        userMarryApply.delete();
    }
}
